﻿using System.Reflection;
using System.Runtime.CompilerServices;

namespace Launcher;

internal static class EntryPointDiscoverer
{
    public static MethodInfo FindStaticEntryMethod(Assembly assembly, string? entryPointFullTypeName = null)
    {
        var candidates = new List<MethodInfo>();

        if (!string.IsNullOrWhiteSpace(entryPointFullTypeName))
        {
            var typeInfo = assembly.GetType(entryPointFullTypeName, false, false)?.GetTypeInfo();
            if (typeInfo == null)
            {
                throw new InvalidProgramException($"Could not find '{entryPointFullTypeName}' specified for Main method. See <StartupObject> project property.");
            }
            FindMainMethodCandidates(typeInfo, candidates);
        }
        else
        {
            foreach (var type in assembly
                         .DefinedTypes
                         .Where(t => t.IsClass)
                         .Where(t => t.GetCustomAttribute<CompilerGeneratedAttribute>() is null))
            {
                FindMainMethodCandidates(type, candidates);
            }
        }

        string MainMethodFullName()
        {
            return string.IsNullOrWhiteSpace(entryPointFullTypeName) ? "Main" : $"{entryPointFullTypeName}.Main";
        }

        if (candidates.Count > 1)
        {
            throw new AmbiguousMatchException(
                $"Ambiguous entry point. Found multiple static functions named '{MainMethodFullName()}'. Could not identify which method is the main entry point for this function.");
        }

        if (candidates.Count == 0)
        {
            throw new InvalidProgramException(
                $"Could not find a static entry point '{MainMethodFullName()}'.");
        }

        return candidates[0];
    }

    private static void FindMainMethodCandidates(TypeInfo type, List<MethodInfo> candidates)
    {
        foreach (var method in type
                     .GetMethods(BindingFlags.Static |
                                 BindingFlags.Public |
                                 BindingFlags.NonPublic)
                     .Where(m =>
                         string.Equals("Main", m.Name, StringComparison.OrdinalIgnoreCase)))
        {
            if (method.ReturnType == typeof(void)
                || method.ReturnType == typeof(int)
                || method.ReturnType == typeof(Task)
                || method.ReturnType == typeof(Task<int>))
            {
                candidates.Add(method);
            }
        }
    }
}